import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';

// 用户接口定义
export interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
  createdAt: string;
}

// 用户状态接口
interface UserState {
  users: User[];
  currentUser: User | null;
  loading: boolean;
  error: string | null;
}

// 初始状态
const initialState: UserState = {
  users: [],
  currentUser: null,
  loading: false,
  error: null,
};

// 异步 action：获取用户列表
export const fetchUsers = createAsyncThunk<
  User[],
  void,
  { rejectValue: string }
>('user/fetchUsers', async (_, { rejectWithValue }) => {
  try {
    // 模拟 API 调用
    const response = await new Promise<User[]>((resolve) => {
      setTimeout(() => {
        resolve([
          {
            id: 1,
            username: 'admin',
            email: 'admin@example.com',
            role: '管理员',
            status: 'active',
            createdAt: '2023-01-01',
          },
          {
            id: 2,
            username: 'user1',
            email: 'user1@example.com',
            role: '用户',
            status: 'active',
            createdAt: '2023-01-02',
          },
          {
            id: 3,
            username: 'user2',
            email: 'user2@example.com',
            role: '用户',
            status: 'inactive',
            createdAt: '2023-01-03',
          },
        ]);
      }, 1000);
    });
    return response;
  } catch (error) {
    return rejectWithValue('获取用户列表失败');
  }
});

// 异步 action：添加用户
export const addUser = createAsyncThunk<
  User,
  Omit<User, 'id' | 'createdAt'>,
  { rejectValue: string }
>('user/addUser', async (userData, { rejectWithValue }) => {
  try {
    // 模拟 API 调用
    const newUser: User = {
      ...userData,
      id: Date.now(),
      createdAt: new Date().toISOString().split('T')[0],
    };
    return newUser;
  } catch (error) {
    return rejectWithValue('添加用户失败');
  }
});

// 异步 action：更新用户
export const updateUser = createAsyncThunk<
  User,
  User,
  { rejectValue: string }
>('user/updateUser', async (userData, { rejectWithValue }) => {
  try {
    // 模拟 API 调用
    return userData;
  } catch (error) {
    return rejectWithValue('更新用户失败');
  }
});

// 异步 action：删除用户
export const deleteUser = createAsyncThunk<
  number,
  number,
  { rejectValue: string }
>('user/deleteUser', async (userId, { rejectWithValue }) => {
  try {
    // 模拟 API 调用
    return userId;
  } catch (error) {
    return rejectWithValue('删除用户失败');
  }
});

// 创建用户 slice
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 设置当前用户
    setCurrentUser: (state, action: PayloadAction<User | null>) => {
      state.currentUser = action.payload;
    },
    // 清除错误
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    // 处理获取用户列表
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.loading = false;
        state.users = action.payload;
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      // 处理添加用户
      .addCase(addUser.fulfilled, (state, action) => {
        state.users.push(action.payload);
      })
      .addCase(addUser.rejected, (state, action) => {
        state.error = action.payload as string;
      })
      // 处理更新用户
      .addCase(updateUser.fulfilled, (state, action) => {
        const index = state.users.findIndex(user => user.id === action.payload.id);
        if (index !== -1) {
          state.users[index] = action.payload;
        }
      })
      .addCase(updateUser.rejected, (state, action) => {
        state.error = action.payload as string;
      })
      // 处理删除用户
      .addCase(deleteUser.fulfilled, (state, action) => {
        state.users = state.users.filter(user => user.id !== action.payload);
      })
      .addCase(deleteUser.rejected, (state, action) => {
        state.error = action.payload as string;
      });
  },
});

// 导出 actions
export const { setCurrentUser, clearError } = userSlice.actions;

// 导出 reducer
export default userSlice.reducer; 